package com.cssw.fyzb.job.executor.service.task;

import com.cssw.fyzb.core.dao.tesk.RuleInstDao;
import com.cssw.fyzb.core.dao.tesk.TaskDao;
import com.cssw.fyzb.core.model.dodb.RuleInst;
import com.cssw.fyzb.core.model.dodb.Task;
import com.cssw.fyzb.core.model.dodb.TaskExec;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author
 */
@Service
public class TaskServiceImpl implements TaskService {

    @Autowired
    private RuleInstDao ruleInstDao;

    @Autowired
    private TaskDao taskDao;


    @Override
    public void updateTask() {
        //获取用户今日任务时长
        List<RuleInst> totalTime = ruleInstDao.getTotalTime();
        //获取mongodb该用户今日视频观看时长
        Integer second = 3600;
        for (RuleInst ruleInst : totalTime) {
            //进行比对 大于
            if (second >= Integer.parseInt(ruleInst.getTotalTiem())) {
                //判断天数是否已到截至日
                List<RuleInst> ruleInsts = ruleInstDao.listRuleInst(ruleInst.getUserId(), RuleInst.STATUS_ONGOING);
                Date date = new Date();
                ruleInsts.forEach(r -> {
                    //剩余产值
                    r.setSurplusValue(r.getSurplusValue().subtract(r.getDayValue()));
                    //日期相等 代表是最后一天 不需要改动 小于加一
                    if (date.before(r.getExpDate())) {
                        r.setAllDay(r.getAllDay() + 1);
                    }
                    //等于结束日期 状态改变
                    if (new SimpleDateFormat("yyyy-MM-dd").format(date).equals(new SimpleDateFormat("yyyy-MM-dd").format(r.getExpDate()))) {
                        r.setStatus(RuleInst.STATUS_TO_COMPLETE);
                    }
                    ruleInstDao.updateRuleInstDao(r);
                    //添加日志
                    this.saveTaskExc(r);
                });
            }
        }
    }

    /**
     * 添加任务执行日志
     *
     * @return
     * @Param
     **/
    private void saveTaskExc(RuleInst ruleInst) {
        TaskExec taskExec = new TaskExec();
        taskExec.setUserId(ruleInst.getUserId());
        taskExec.setInstId(ruleInst.getInstId());
        Task task = taskDao.getTask(ruleInst.getUserId());
        //完成时长
        taskExec.setTotalTime(task.getTaskTime() * ruleInst.getAllDay());
        taskExec.setCreateTime(new Date());
    }
}
